package com.blaze.framework.core.boot.argumentresolver;

import com.blaze.framework.core.util.constants.TokenConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Token user id 参数解析器
 * @author created by Zhou Zongbo on 2025/5/26.
 */
public class TokenUserIdArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameter().getType().equals(Long.class) && TokenConstants.REQUEST_PARAM_TOKEN_USER_ID.equals(parameter.getParameterName());
    }

    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  @NonNull NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {

        try {
            String tokenUserId = webRequest.getHeader(TokenConstants.TOKEN_HEADER_USER_ID);
            if (StringUtils.isEmpty(tokenUserId)) {
                return null;
            }
            return Long.parseLong(tokenUserId);
        } catch (Exception ex) {
            return null;
        }

    }
}
